﻿using MDK.Common;
using System;

namespace MDK.Device.Components
{
    public interface ISensor : IPlcDeviceComponent
    {
        bool IsActive(int duration = 0, bool IsWriteLog=true);
    }

    public class Sensor : ISensor
    {
        public IPlcDevice Device { get; }
        public PlcAddress Addr { get; }
        public bool ActiveValue { get; }
        public Sensor(IPlcDevice device, PlcAddress address, bool activeVal = true)
        {
            Device = device;
            Addr = address;
            ActiveValue = activeVal;
        }

        public bool IsActive(int duration = 0, bool IsWriteLog = true)
        {
            var st = DateTime.Now;
            while (Device.PLC.BitIsSet(Addr) == ActiveValue)
            {
                if (IsWriteLog)
                    HandoverData.SandStateChangeData(EnumCmdCode.SensorState, ((MitsubishiPlc)Device.PLC).PlcIP, this.GetType().Name, Addr.ToString(), 1);
                if ((DateTime.Now - st).TotalMilliseconds >= duration) return true;
            }
            HandoverData.SandStateChangeData(EnumCmdCode.SensorState, ((MitsubishiPlc)Device.PLC).PlcIP, this.GetType().Name, Addr.ToString(), 0);
            return false;
        }

    }
}